<?php
/**
 * @title 54. 螺旋矩阵 - 遍历
 * @author start2004
 */

class Solution {

    /**
     * @param Integer[][] $matrix
     * @return Integer[]
     */
    function spiralOrder($matrix) {
        /**
         *   →  →  →
         *   ↑     ↓
         *   ↑     ↓
         *   ←  ←  ←
         *
         * @since 2020-07-22 极端情况排除
         */
        $h = count($matrix);
        if($h == 0){
            return [];
        } else {}
        $w = count($matrix[0]);
        if($w == 0){
            return [];
        } else {}

        /**
         * @since 2020-07-22 结果集
         */
        $result = [];

        /**
         * @since 2020-07-22 开始逆时针
         */
        $maxW = $w;
        $maxH = $h;
        for($i=0, $iMax = (min($w, $h)-1)>>1; $i<=$iMax; $i++){
            $maxW--;
            $maxH--;

            /**
             * @since 2020-07-22 横向
             */
            for ($j=$i; $j<=$maxW; $j++){
                $result[] = $matrix[$i][$j];
            }

            /**
             * @since 2020-07-22 纵向
             */
            for($j=$i+1; $j<=$maxH; $j++){
                $result[] = $matrix[$j][$maxW];
            }

            /**
             * @since 2020-07-22 反横向, 高度至少2行
             */
            if($maxH != $i){
                for($j=$maxW-1; $j>=$i; $j--){
                    $result[] = $matrix[$maxH][$j];
                }
            }

            /**
             * @since 2020-07-22 反纵向, 宽度至少2行
             */
            if($maxW != $i){
                for($j=$maxH-1; $j>$i; $j--){
                    $result[] = $matrix[$j][$i];
                }
            } else {}
        }

        /**
         * @return
         */
        return $result;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.22_5.php
 */
$datas = [
    [
        [ 1, 2, 3 ],
        [ 4, 5, 6 ],
        [ 7, 8, 9 ]
    ],
    [
        [1, 2, 3, 4],
        [5, 6, 7, 8],
        [9,10,11,12]
    ],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->spiralOrder($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
